<template>
  <div class="approval-test-container">
    <h2>审核状态测试页面</h2>
    
    <!-- 测试数据表格 -->
    <el-card class="test-card">
      <div class="card-header">
        <h3>测试数据</h3>
        <el-button type="primary" @click="loadTestData">加载测试数据</el-button>
      </div>
      
      <el-table :data="testData" border stripe>
        <el-table-column prop="outboundId" label="出库ID" width="100" />
        <el-table-column prop="outboundOrderNumber" label="出库单号" width="200" />
        <el-table-column prop="outboundType" label="出库类型" width="120" />
        <el-table-column prop="outboundTime" label="出库时间" width="180" />
        <el-table-column prop="Approval" label="审核状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getApprovalStatusType(row.Approval)">
              {{ getApprovalStatusText(row.Approval) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="200" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="success" size="small" @click="testApprove(row, '审核通过')">
              通过
            </el-button>
            <el-button type="danger" size="small" @click="testApprove(row, '驳回')">
              驳回
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 调试信息 -->
    <el-card class="debug-card">
      <div class="card-header">
        <h3>调试信息</h3>
        <el-button type="warning" @click="clearLogs">清空日志</el-button>
      </div>
      
      <div class="debug-logs">
        <div v-for="(log, index) in debugLogs" :key="index" class="log-item">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-level" :class="log.level">{{ log.level }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  getAllOutboundOrders, 
  updateApprovalStatus,
  type OutboundOrder 
} from '@/api/outboundOrder'

// 测试数据
const testData = ref<OutboundOrder[]>([])
const debugLogs = ref<Array<{time: string, level: string, message: string}>>([])

// 添加日志
const addLog = (level: string, message: string) => {
  const time = new Date().toLocaleTimeString()
  debugLogs.value.unshift({ time, level, message })
  console.log(`[${level}] ${message}`)
}

// 清空日志
const clearLogs = () => {
  debugLogs.value = []
}

// 获取审核状态文本
const getApprovalStatusText = (status: string) => {
  if (!status || status.trim() === '' || status === null || status === undefined) {
    return '待审核'
  }
  
  const trimmedStatus = status.trim()
  
  switch (trimmedStatus) {
    case '待审核':
    case '0':
      return '待审核'
    case '审核通过':
    case '通过':
    case '1':
      return '审核通过'
    case '驳回':
    case '拒绝':
    case '2':
      return '驳回'
    default:
      return '待审核'
  }
}

// 获取审核状态标签类型
const getApprovalStatusType = (status: string) => {
  if (!status || status.trim() === '' || status === null || status === undefined) {
    return 'warning'
  }
  
  const trimmedStatus = status.trim()
  
  switch (trimmedStatus) {
    case '待审核':
    case '0':
      return 'warning'
    case '审核通过':
    case '通过':
    case '1':
      return 'success'
    case '驳回':
    case '拒绝':
    case '2':
      return 'danger'
    default:
      return 'warning'
  }
}

// 加载测试数据
const loadTestData = async () => {
  try {
    addLog('info', '开始加载测试数据...')
    
    const response = await getAllOutboundOrders()
    
    if (response.code === 200) {
      testData.value = response.data.map((item: OutboundOrder) => {
        addLog('info', `加载记录: ID=${item.outboundId}, 状态=${item.Approval}`)
        
        // 确保审核状态字段存在
        if (!item.Approval || item.Approval === null || item.Approval === undefined) {
          item.Approval = '待审核'
          addLog('warn', `记录 ${item.outboundId} 审核状态为空，设置为待审核`)
        }
        
        return item
      })
      
      addLog('success', `成功加载 ${testData.value.length} 条记录`)
      ElMessage.success('测试数据加载成功')
    } else {
      addLog('error', `加载失败: ${response.msg}`)
      ElMessage.error(response.msg || '加载失败')
    }
  } catch (error) {
    addLog('error', `加载异常: ${error}`)
    console.error('加载测试数据失败:', error)
    ElMessage.error('加载失败')
  }
}

// 测试审核
const testApprove = async (row: OutboundOrder, status: string) => {
  try {
    addLog('info', `开始审核: ID=${row.outboundId}, 目标状态=${status}`)
    addLog('info', `当前状态: ${row.Approval}`)
    
    const params = {
      outboundId: row.outboundId,
      Approval: status,
      modifiedBy: 'test-user',
      remarks: `测试审核 - ${status}`
    }
    
    addLog('info', `审核参数: ${JSON.stringify(params)}`)
    
    const response = await updateApprovalStatus(params)
    
    addLog('info', `审核响应: ${JSON.stringify(response)}`)
    
    if (response.code === 200) {
      addLog('success', `审核成功: ${row.outboundOrderNumber} -> ${status}`)
      
      // 更新本地数据
      const index = testData.value.findIndex(item => item.outboundId === row.outboundId)
      if (index !== -1) {
        testData.value[index].Approval = status
        addLog('info', `本地数据已更新`)
      }
      
      ElMessage.success('审核成功')
      
      // 重新加载数据以确保状态正确
      setTimeout(() => {
        loadTestData()
      }, 1000)
    } else {
      addLog('error', `审核失败: ${response.msg}`)
      ElMessage.error(response.msg || '审核失败')
    }
  } catch (error) {
    addLog('error', `审核异常: ${error}`)
    console.error('审核失败:', error)
    ElMessage.error('审核失败')
  }
}
</script>

<style scoped>
.approval-test-container {
  padding: 20px;
}

.test-card, .debug-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.debug-logs {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background-color: #f5f7fa;
}

.log-item {
  display: flex;
  margin-bottom: 5px;
  font-family: monospace;
  font-size: 12px;
}

.log-time {
  color: #909399;
  margin-right: 10px;
  min-width: 80px;
}

.log-level {
  margin-right: 10px;
  min-width: 60px;
  font-weight: bold;
}

.log-level.info {
  color: #409eff;
}

.log-level.success {
  color: #67c23a;
}

.log-level.warn {
  color: #e6a23c;
}

.log-level.error {
  color: #f56c6c;
}

.log-message {
  flex: 1;
  word-break: break-all;
}
</style>
